<template>
  <div class="body">
    <!-- 头部 -->
    <home-head />
    <!-- 上拉刷新 -->
    <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
    <!-- 轮播图 -->
    <carousel :banners="banners"/>
    <!-- 宫格导航 -->
    <grid-nav :cates="cates"/>
    <!-- 推荐商品+下拉加载 -->
    <van-list
      v-model="loading"
      :finished="finished"
      :offset="50"
      finished-text="没了，没了，去别家吧"
      @load="onLoad">
    <recommend-item :recommend="recommend" @detail="details" />
    </van-list>
    </van-pull-refresh>
    <!-- 底部 -->
    <tabbar />
    <!-- 副标 -->
     <message />
  </div>
</template>

<script>
import Message from '../../components/Message'
import Tabbar from '../../components/Tabbar.vue'
import HomeHead from './components/HomeHead.vue'
import RecommendItem from './components/RecommendItem'
import Carousel from './components/Carousel'
import GridNav from './components/GridNav.vue'
import { fetchHomeBanner, fetchCates, recommendItem } from '../../api/index'
export default {
  name: 'Home',
  data () {
    return {
      banners: [],
      cates: [],
      recommend: [],
      page: 1,
      pageSize: 4,
      loading: false,
      finished: false,
      isLoading: false
    }
  },
  created () {
    // 轮播
    this.fetchBanner()
    // 宫格导航
    this.fetchCate()
  },
  methods: {
    // 详情页
    details (id) {
      this.$router.push({
        path: '/detail',
        query: {
          id
        }
      })
    },
    // 下拉刷新
    onRefresh () {
      // 遇到上拉加载 初始化
      // 将数据清空
      this.recommend = []
      // 回到第一页
      this.page = 1
      // 将上拉加载到达底部状态变成false
      this.finished = false
      // 用户下拉刷新了
      // 重新请求列表接口函数 成功之后 将isLoading变成false 页面上去
      this.recommendItem()
      this.page++
    },
    // 上拉加载
    onLoad () {
      // 推荐商品
      this.recommendItem()
      this.page++
    },
    // 获取推荐商品数据
    recommendItem () {
      recommendItem({
        categoryId: 72399,
        page: this.page,
        pageSize: this.pageSize
      }).then(res => {
        this.isLoading = false
        this.loading = false
        if (res.data.code === 0) {
          // 分页数据合并
          this.recommend = [
            ...this.recommend,
            ...res.data.data.result
          ]
        }
        if (res.data.code === 700) {
          // 已经到达最后一页 已经没有数据了
          this.finished = true
        }
      })
    },
    // 宫格导航数据
    fetchCate () {
      fetchCates().then(res => {
        if (res.data.code === 0) {
          // console.log(res)
          this.cates = res.data.data
        }
      })
    },
    // 获取轮播数据
    fetchBanner () {
      fetchHomeBanner().then((res) => {
        // console.log(res)
        if (res.data.code === 0) {
          this.banners = res.data.data
        }
      })
    }
  },
  components: { Tabbar, Message, HomeHead, RecommendItem, Carousel, GridNav }
}
</script>

<style lang="scss" scoped>
.body{
  padding-bottom: 1rem;
}
</style>
